﻿using System.Collections.Concurrent;

namespace UtilZ.Dotnet.Ex.Communication.Net.BMQ
{
    /// <summary>
    /// BMQ消息对象池
    /// </summary>
    public class BMQMessagePool
    {
        /// <summary>
        /// 默认BMQ消息管理器
        /// </summary>
        public static readonly BMQMessagePool Default;

        static BMQMessagePool()
        {
            Default = new BMQMessagePool();
        }

        private ConcurrentBag<BMQBlobMessage> _blobMessages = new ConcurrentBag<BMQBlobMessage>();
        private ConcurrentBag<BMQTextMessage> _textMessages = new ConcurrentBag<BMQTextMessage>();

        /// <summary>
        /// 租借一个BMQBlobMessage消息
        /// </summary>
        /// <returns>BMQBlobMessage消息</returns>
        public BMQBlobMessage RentBlobMessage()
        {
            BMQBlobMessage message;
            if (this._blobMessages.TryTake(out message))
            {
                return message;
            }

            return new BMQBlobMessage();
        }

        /// <summary>
        /// 返回一个BMQBlobMessage消息
        /// </summary>
        /// <param name="message">BMQBlobMessage消息</param>
        public void ReturnBlobMessage(BMQBlobMessage message)
        {
            this._blobMessages.Add(message);
        }




        /// <summary>
        /// 租借一个BMQTextMessage消息
        /// </summary>
        /// <returns>BMQTextMessage消息</returns>
        public BMQTextMessage RentTextMessage()
        {
            BMQTextMessage message;
            if (this._textMessages.TryTake(out message))
            {
                return message;
            }

            return new BMQTextMessage();
        }

        /// <summary>
        /// 返回一个BMQTextMessage消息
        /// </summary>
        /// <param name="message">BMQTextMessage消息</param>
        public void ReturnTextMessage(BMQTextMessage message)
        {
            this._textMessages.Add(message);
        }

    }

}
